package com.nit.bike.service.basic.impl;

import com.nit.bike.dto.basic.StationDTO;
import com.nit.bike.dto.utils.PagingDTO;
import com.nit.bike.dto.utils.TableReqDTO;
import com.nit.bike.dto.utils.TableRspDTO;
import com.nit.bike.entity.basic.StationEntity;
import com.nit.bike.mapper.basic.StationMapper;
import com.nit.bike.service.basic.StationService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class StationServiceImpl implements StationService {

    @Resource
    private StationMapper stationMapper;

    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = stationMapper.count4Table(
                tableReqDTO.parseQueryParam("stationName"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                stationMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("stationName"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()));
        return new TableRspDTO(pagingDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(StationDTO stationDTO) throws Exception {
        MapperFactory factory = new DefaultMapperFactory.Builder().build();
        StationEntity entity = factory.getMapperFacade().map(stationDTO, StationEntity.class);
        entity.setGmtCreate(new Date());
        return stationMapper.insertSelective(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(StationDTO stationDTO) throws Exception {
        MapperFactory factory = new DefaultMapperFactory.Builder().build();
        StationEntity entity = factory.getMapperFacade().map(stationDTO, StationEntity.class);
        return stationMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String stationIds) throws Exception {
        String[] arrayStationId = stationIds.split(",");
        for (String s : arrayStationId) {
            stationMapper.deleteByPrimaryKey(Long.parseLong(s));
        }
        return arrayStationId.length;
    }

    @Override
    public List<StationDTO> listStation() throws Exception {
        return stationMapper.listStation();
    }
}
